// @before-stub-for-debug-begin
#include <vector>
#include <string>
#include <unordered_map>
#include "commoncppproblem889.h"

using namespace std;
// @before-stub-for-debug-end

/*
 * @lc app=leetcode.cn id=889 lang=cpp
 *
 * [889] 根据前序和后序遍历构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    unordered_map<int,int> index;
public:
    TreeNode* build(vector<int>& preorder, vector<int>& postorder, int preStart, int preEnd, int postStart, int postEnd) {
        if (preStart > preEnd) return nullptr;
        TreeNode* root = new TreeNode(preorder[preStart]);
        if (preStart == preEnd) return root;
        int post_left_root_idx = index[preorder[preStart+1]];
        int left_subtree_size = post_left_root_idx - postStart + 1;

        root->left = build(preorder, postorder, preStart + 1, preStart + left_subtree_size, postStart, post_left_root_idx);
        root->right = build(preorder, postorder, preStart + left_subtree_size + 1, preEnd, post_left_root_idx + 1, postEnd - 1);
        return root;
    }

    TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {
        int n = preorder.size();
        for (int i = 0; i < n; i++) {
            index[postorder[i]] = i;
        }
        return build(preorder, postorder, 0, n - 1, 0, n - 1);
    }
};
// @lc code=end

